package hot;

import java.nio.ByteBuffer;

/**
 * @author way
 * @create 2025-04-02 17:01
 */
public class _322_coinChange {
    public int coinChange(int[] coins, int amount) {
        //dp代表当前兑换的最少次数 dp[0][i]钱为0，凑成金额i的次数  dp[i][0]凑成0金额的次数
        int[][] dp = new int[coins.length + 1][amount + 1];
        int max = amount + 1;

        for (int i = 0; i <= amount; i++) {
            dp[0][i] = max; // 不会超过max
        }
// 分配 10M 堆外内存

        ByteBuffer buffer = ByteBuffer.allocateDirect(10 * 1024 * 1024);
        buffer.rewind();
        byte b = buffer.get();
        for (int i = 1; i <= coins.length; i++) {
            for (int j = 1; j <= amount; j++) {
                if (coins[i - 1] > j) dp[i][j] = dp[i - 1][j];
                else dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1);
            }
        }
        int res = dp[coins.length][amount];
        return res == max ? -1 : res;
    }
}
